package com.tinyseed.emcp.api.app.sharding;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Range;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicInteger;

/*
* 范围查询
*
*
* */
@Slf4j
public class DateRangeShardingAlgorithm implements RangeShardingAlgorithm<Date> {
    private static DateTimeFormatter sdf = DateTimeFormatter.ofPattern("yyyyMM", Locale.CHINA);
    private static final String SEPERATOR = "_";//表名分隔符
    private static Date lowwerDate = null;

    static {
        lowwerDate = DateUtil.parseDate("2020-05-01");
    }

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames,
                                         RangeShardingValue<Date> shardingValue) {
        Collection<String> tableSet = Sets.newConcurrentHashSet();
        String logicTableName = shardingValue.getLogicTableName();
        Range<Date> dates = shardingValue.getValueRange();
        Date lowDate =  DateUtil.truncate( dates.lowerEndpoint(), DateField.MONTH );
        Date upperDate = DateUtil.truncate(dates.upperEndpoint(),DateField.MONTH) ;//为了把当前月份加进来
        AtomicInteger i = new AtomicInteger(0);
        while(DateUtil.offsetMonth(lowDate, i.get()).compareTo(upperDate)<=0){
            Date date = DateUtil.offsetMonth(lowDate, i.getAndAdd(1));
            if(date.before(lowwerDate)){//早于其实日期的，都从默认的表里面找
                tableSet.add(logicTableName);
            }else{
                tableSet.add(logicTableName+SEPERATOR+date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().format(sdf));
            }
        }
        log.info("要查询的表集合:{}", JSONObject.toJSONString(tableSet));
        return tableSet;
    }

}